package com.cscj.android.repository.db.dao

import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Upsert
import com.cscj.android.repository.db.entity.ShortCutCategoryEntity
import com.cscj.android.repository.db.entity.ShortCutEntity
import com.cscj.android.repository.db.entity.ShortCutEntryEntity
import com.cscj.android.repository.uidata.ShortCutUIData
import kotlinx.coroutines.flow.Flow

@Dao
interface ShortCutDao {

    @Upsert
    suspend fun upsertCategories(categories: List<ShortCutCategoryEntity>)

    @Upsert
    suspend fun upsertShortCuts(shortCuts: List<ShortCutEntity>)

    @Upsert
    suspend fun upsertShortCutEntries(shortCutEntries: List<ShortCutEntryEntity>)

    @Upsert
    suspend fun upsertShortCutEntry(shortCutEntry: ShortCutEntryEntity)

    @Query("delete from short_cut_category")
    suspend fun deleteCategories()

    @Query("delete from short_cut")
    suspend fun deleteShortCuts()

    @Query("update short_cut set added = 1 where id = :shortCutId")
    suspend fun markShortCutAdded(shortCutId: Int)

    @Query("delete from short_cut_entry where id = :id")
    suspend fun deleteShortCutEntry(id: Int)

    @Query("delete from short_cut_entry")
    suspend fun deleteShortCutEntries()

    @Transaction
    @Query("select * from short_cut_category order by sortOrder")
    fun shortCutListFlow(): Flow<List<ShortCutUIData>>

    @Query("select * from short_cut_entry")
    fun shortCutEntriesFlow(): Flow<List<ShortCutEntryEntity>>

    @Query("select max(sortOrder) from short_cut_entry")
    suspend fun getMaxShortCutEntrySortOrder(): Int


    /**
     * 查询根目录的添加状态
     */
    @Query("select count(1) from short_cut_entry where type = :type and isRoot = 1")
    suspend fun getRootEntryCount(type:Int): Int

    @Query("select count(1) from short_cut_entry where type = :type and link = :url")
    suspend fun getEntryCount(type: Int, url: String): Int

}